package com.vehicle.stock.provider.serviceimpl;

import com.google.common.collect.Maps;
import com.vehicle.common.util.Jsons;
import com.vehicle.stock.api.service.SeckillService;
import com.vehicle.stock.provider.mapper.SeckillMapper;
import com.vehicle.stock.provider.mapper.SuccessKilledMapper;
import com.vehicle.stock.provider.rocketmq.producer.TransactionExecuterImpl;
import com.vehicle.stock.provider.rocketmq.producer.TransactionProducer;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.LocalTransactionExecuter;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

/**
 * Created by yantingbin on 2017/8/11.
 */
@Service
public class SeckillServiceImpl implements SeckillService {
    private static final Logger LOGGER= LoggerFactory.getLogger(SeckillService.class);

    @Autowired
    private TransactionProducer transactionProducer;

    @Autowired
    private LocalTransactionExecuter  tranExecuter;

    @Autowired
    private SeckillMapper seckillMapper;
    @Autowired
    private SuccessKilledMapper successKilledMapper;

    @Override
    public void handleSeckill(long seckillId, long userPhone) {
        try {
            Map<String,Object> map= Maps.newHashMap();
            map.put("seckillId",seckillId);
            map.put("userPhone",userPhone);
            Message msg =new Message("SeckillTopic", "SeckillTag", "SeckillKEY" +seckillId , Jsons.toJson(map).getBytes(RemotingHelper.DEFAULT_CHARSET));
            LOGGER.info("Send message info:{}",Jsons.toJson(map).getBytes(RemotingHelper.DEFAULT_CHARSET));
            SendResult sendResult = transactionProducer.getMqProducer().sendMessageInTransaction(msg, tranExecuter, null);

        } catch (MQClientException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Transactional
    @Override
    public boolean executeSeckill(long seckillId, long userPhone) {
        // 记录购买行为
        int insertCount = successKilledMapper.insertSuccessKilled(seckillId, userPhone);

        LOGGER.info("recording success killed info,number of rows affected {}",insertCount);

        //int i=10/0;

        return insertCount>0;
    }

    @Transactional
    @Override
    public boolean reduceSeckill(long seckillId, Date now) {
        int updateCount= seckillMapper.reduceNumber(seckillId,now);
        LOGGER.info("recording reduce seckill number,number of rows affected {}",updateCount);
        return updateCount>0;
    }
}
